package com.xgk.boot.module.core.service.truck;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import com.xgk.boot.framework.common.constant.ErrorCodeConstants;
import com.xgk.boot.framework.common.exception.util.ServiceExceptionUtil;
import com.xgk.boot.framework.common.pojo.PageResult;
import com.xgk.boot.framework.common.util.object.BeanUtils;
import com.xgk.boot.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xgk.boot.module.core.controller.admin.truck.vo.TruckOrderFeeDetailReqVo;
import com.xgk.boot.module.core.controller.admin.truck.vo.TruckOrderFeeDetailVO;
import com.xgk.boot.module.core.controller.admin.truck.vo.TruckOrderOtherReqVO;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrderFeeDetailDO;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrdersDO;
import com.xgk.boot.module.core.dal.iservice.truck.TruckOrderFeeDetailService;
import com.xgk.boot.module.core.dal.mapper.truck.TruckOrderFeeDetailMapper;
import com.xgk.boot.module.core.service.customer.CustomerBalanceServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.xgk.boot.module.core.enums.LogRecordConstants.*;

/**
 * 订单费用明细 服务实现
 */
@Slf4j
@Service
public class TruckOrderFeeDetailServiceImpl extends ServiceImpl<TruckOrderFeeDetailMapper, TruckOrderFeeDetailDO> implements TruckOrderFeeDetailService {

    @Resource
    private CustomerBalanceServiceImpl customerBalanceService;

    public PageResult<TruckOrderFeeDetailDO> pageOrdersFees(TruckOrderOtherReqVO orderOtherReqVO){
        if(orderOtherReqVO == null || StrUtil.isBlank(orderOtherReqVO.getOrderCode())){
            return new PageResult<>();
        }
        LambdaQueryWrapperX<TruckOrderFeeDetailDO> boxWrapperX = new LambdaQueryWrapperX<>();
        boxWrapperX.eq(TruckOrderFeeDetailDO::getOrderCode, orderOtherReqVO.getOrderCode());
        boxWrapperX.orderByDesc(TruckOrderFeeDetailDO::getCreateTime);
        Page<TruckOrderFeeDetailDO> page=new Page<>(orderOtherReqVO.getCurrent(),orderOtherReqVO.getPageSize());
        Page<TruckOrderFeeDetailDO> pageRes = this.page(page, boxWrapperX);

        return new PageResult<>(pageRes.getRecords(), pageRes.getTotal(), orderOtherReqVO.getCurrent(), orderOtherReqVO.getPageSize());
    }

    public PageResult<TruckOrderFeeDetailDO> pageListOrdersFees(TruckOrderFeeDetailReqVo orderFeeDetailReqVo){
        if(orderFeeDetailReqVo == null ){
            return new PageResult<>();
        }
        LambdaQueryWrapperX<TruckOrderFeeDetailDO> feeWrapperX = new LambdaQueryWrapperX<>();
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getOrderCode, orderFeeDetailReqVo.getOrderCode());
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getProductCode, orderFeeDetailReqVo.getProductCode());
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getReferenceNo, orderFeeDetailReqVo.getReferenceNo());
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getTrackingNumber, orderFeeDetailReqVo.getTrackingNumber());
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getCustomerCode, orderFeeDetailReqVo.getCustomerCode());
        if(orderFeeDetailReqVo.getBeginCreateTime() != null && orderFeeDetailReqVo.getBeginCreateTime() != null) {
            feeWrapperX.between(TruckOrderFeeDetailDO::getCreateTime, orderFeeDetailReqVo.getBeginCreateTime(), orderFeeDetailReqVo.getEndCreateTime());
        }
        feeWrapperX.orderByDesc(TruckOrderFeeDetailDO::getCreateTime);
        feeWrapperX.orderByAsc(TruckOrderFeeDetailDO::getUpdateTime);
        Page<TruckOrderFeeDetailDO> page=new Page<>(orderFeeDetailReqVo.getCurrent(),orderFeeDetailReqVo.getPageSize());
        Page<TruckOrderFeeDetailDO> pageRes = this.page(page, feeWrapperX);

        return new PageResult<>(pageRes.getRecords(), pageRes.getTotal(), orderFeeDetailReqVo.getCurrent(), orderFeeDetailReqVo.getPageSize());
    }


    /**
     * 增加订单扩展账单信息
     *
     * @param feeDetailVO
     * @return
     */
    @Override
    @Transactional
    @LogRecord(type = SYSTEM_ORDER_TYPE, subType = SYSTEM_ORDER_FEE_CREATE_TYPE, bizNo = "{{#fee.orderCode}}",
            success = SYSTEM_ORDER_FEE_CREATE_SUCCESS)
    public boolean addOrderFee(TruckOrderFeeDetailVO feeDetailVO){
        String orderCode = feeDetailVO.getOrderCode();
        LambdaQueryWrapperX<TruckOrderFeeDetailDO> feeWrapperX = new LambdaQueryWrapperX<>();
        feeWrapperX.eqIfPresent(TruckOrderFeeDetailDO::getOrderCode, feeDetailVO.getOrderCode());
        TruckOrderFeeDetailDO one = this.getOne(feeWrapperX);
        if(one ==null){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS,feeDetailVO.getOrderCode() +" base fee");
        }
        TruckOrderFeeDetailDO truckOrderFeeDetailDO = BeanUtils.toBean(feeDetailVO, TruckOrderFeeDetailDO.class);
        truckOrderFeeDetailDO.setIsExtend(1);
        truckOrderFeeDetailDO.setIsDeduct(0);
        truckOrderFeeDetailDO.setCreateTime(one.getCreateTime());
        this.saveOrUpdate(truckOrderFeeDetailDO);
        LogRecordContext.putVariable("fee", truckOrderFeeDetailDO);
        return true;
    }


    @Override
    @Transactional
    @LogRecord(type = SYSTEM_ORDER_TYPE, subType = SYSTEM_ORDER_FEE_DELETE_TYPE, bizNo = "{{#fee.orderCode}}",
            success = SYSTEM_ORDER_FEE_DELETE_SUCCESS)
    public boolean deleteOrderFee(String id){
        TruckOrderFeeDetailDO byId = this.getById(id);
        if(byId ==null){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS,"fee");
        }
        if(byId.getIsExtend().equals(0)){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_NO_DELETE,"basic fee");
        }
        this.removeById(id);
        LogRecordContext.putVariable("fee", byId);
        return true;
    }

    /**
     * 删除基础收费
     * 一版为取消订单后删除相关收费项
     * @param order
     * @return
     */
    @Override
    @Transactional
    @LogRecord(type = SYSTEM_ORDER_TYPE, subType = SYSTEM_ORDER_FEE_DELETE_TYPE, bizNo = "{{#orderCode}}",
            success = SYSTEM_ORDER_BASE_FEE_DELETE_SUCCESS)
    public boolean deleteFeeByOrderCode(TruckOrdersDO order){
        if(order ==null){
            return true;
        }
        LambdaQueryWrapperX<TruckOrderFeeDetailDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(TruckOrderFeeDetailDO::getOrderCode, order.getOrderCode());
        List<TruckOrderFeeDetailDO> list = this.list(queryWrapperX);
        if(list.isEmpty()){
            return true;
        }
        for (TruckOrderFeeDetailDO truckOrderFeeDetailDO : list) {
            this.removeById(truckOrderFeeDetailDO.getOfdId());
            if(truckOrderFeeDetailDO.getIsDeduct().equals(1)){
                //如果已扣除，则对应回退费用
                customerBalanceService.rebackFeeToCustomeFees(truckOrderFeeDetailDO.getOfdAmount(),order.getCustomerCode(),order);
                log.info("删除订单账单：{} 账单信息，回退金额{}",truckOrderFeeDetailDO.getOfdId(),truckOrderFeeDetailDO.getOfdAmount().doubleValue());
            }
        }
        log.info("删除订单:{}账单信息",order.getOrderCode());
        LogRecordContext.putVariable("orderCode", order.getOrderCode());
        return true;
    }
}